package util

import (
	"database/sql"
	"errors"
	"strconv"
	"strings"
)

func GetMinAndMaxFromSlice(t []int32) (int32, int32, error) {
	if len(t) == 0 {
		return 0, 0, errors.New("slice 至少包含一个元素")
	}
	min := t[0]
	max := t[0]
	for _, i := range t[1:] {
		if min > i {
			min = i
		}
		if max < i {
			max = i
		}
	}
	return min, max, nil
}

func GetString(t []int32, sep string) string {
	if len(t) == 0 {
		return ""
	}
	var s []string
	for _, i := range t {
		s = append(s, strconv.Itoa(int(i)))
	}
	return strings.Join(s, sep)
}

func GetUniqueSlice(t []int32) []int32 {
	d := make(map[int32]bool)
	r := make([]int32, 0)
	for _, i := range t {
		if !d[i] {
			d[i] = true
			r = append(r, i)
		}
	}
	return r
}

func HasDuplicate(t []int32) bool {
	uniqueIds := GetUniqueSlice(t)
	return len(uniqueIds) != len(t)
}

func GetUniqueSliceString(t []string) []string {
	d := make(map[string]bool)
	r := make([]string, 0)
	for _, i := range t {
		if !d[i] {
			d[i] = true
			r = append(r, i)
		}
	}
	return r
}

func HasDuplicateString(s []string) bool {
	uniquesStr := GetUniqueSliceString(s)
	return len(uniquesStr) != len(s)
}

func ConvertNullString(nullString sql.NullString) string {
	if !nullString.Valid {
		return ""
	}
	return nullString.String
}

func ConvertNullInt64(nullInt sql.NullInt64) string {
	if !nullInt.Valid {
		return ""
	}
	return strconv.Itoa(int(nullInt.Int64))
}

func AdaptNullString(s string) sql.NullString {
	if s == "" {
		return sql.NullString{}
	}
	return sql.NullString{
		String: s,
		Valid:  true,
	}
}

func AdaptNullInt64(s string) sql.NullInt64 {
	if s == "" {
		return sql.NullInt64{}
	}
	v, _ := strconv.Atoi(s)
	return sql.NullInt64{
		Int64: int64(v),
		Valid: true,
	}
}
